<?php
/**
 * Author:   tangxiaowen
 * Email:    846506584@qq.com
 * Date:     2021/3/10 0010 16:07
 * Describe: 企业微信服务模块 - 标签类
 */

namespace app\common\server\corp;

use think\exception\ValidateException;

class Tag extends Base
{
    /**
     * @var int 缓存时间/秒
     */
    private $cacheTime = 86400;

    /**
     * @var string 默认标签名称
     */
    private $defaultTagName = '渠道1';

    /**
     * @var string 默认标签组组名称
     */
    private $defaultGroupTagName = '气质范渠道';

    /**
     * @var string 添加标签url
     */
    private $addTagUrl = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_corp_tag?access_token=%s';

    /**
     * @var string 获取所有标签url
     */
    private $getCorpAllTagUrl = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_corp_tag_list?access_token=%s';

    /**
     * 获取企业所有标签
     */
    public function getCorpAllTag(string $corpId)
    {
        $corpAllTag = cache($corpId . 'corpAllTag');
        if(!$corpAllTag){
            $res = $this->curlFn(sprintf($this->getCorpAllTagUrl, (new Token())->getAuthCorpAccessToken($corpId)), [
                'tag_id' => [],
                'group_id' => [],
            ], true);
            $res = $this->setResponse($res);
            if(isset($res['tag_group'])){
                cache($corpId . 'corpAllTag', $res['tag_group'], $this->cacheTime);
            }else{
                check_exception($res['errmsg']?? '');
            }
            $corpAllTag = cache($corpId . 'corpAllTag');
        }
        return $corpAllTag?? [];
    }

    /**
     * 获取企业微信默认标签Id
     * @param string $corpId
     * @param string $name
     * @throws ValidateException
     * @return string
     */
    public function getCorpDefaultTagId(string $corpId): string
    {
        $corpAllTag = $this->getCorpAllTag($corpId);
        if(!in_array($this->defaultGroupTagName, array_column($corpAllTag, 'group_name'))){
            $res = $this->curlFn(sprintf($this->addTagUrl, (new Token())->getAuthCorpAccessToken($corpId)), [
                'group_id' => '',
                'group_name' => $this->defaultGroupTagName,
                'tag' => [
                    ['name' => $this->defaultTagName]
                ]
            ], true);
            /** @var \app\common\server\corp\Tag getCorpAllTag */
            cache($corpId . 'corpAllTag', null);
            $res = $this->setResponse($res);
            $tag = $res['tag_group']['tag'][0]['id']?? '';
        }else{
            foreach ($corpAllTag as $v){
                if($v['group_name'] == $this->defaultGroupTagName){
                    $tag = $v['tag'][0]['id']?? '';
                }
            }

        }

        return $tag?? '';
    }

}